const webpack = require('webpack')
const path = require('path')
const fs = require('fs')
const glob = require("glob")
const myconf = require('./my.config')
const WebpackInlineJsPlugin = require('./my.plug')

const build = process.argv.indexOf('--env=build') !== -1
const prod = process.argv.indexOf('--env=prod') !== -1
const {
  isModified
} = require('./file.syn')

let plugins = [new webpack.optimize.ModuleConcatenationPlugin()]

plugins.push(new WebpackInlineJsPlugin()) //此插件将js内嵌到html中

if (build || prod) {
  plugins.push(
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false,
        drop_console: true,
        pure_funcs: ['console.log']
      },
      output: {
        comments: false,
      },
    })
  )
}


/****---- 需要改变下面配置 ----***/
const TARGET_DIR = myconf.target_project  //目标目录，生成的文件将拷贝到这个目录下
const tatdir = myconf.target_subdir //指定拷贝到那个文件夹下
const srcdir = myconf.source_jsdir  //设定源js目录

//////////////////////////////////////////

//TARGET_DIR = __dirname

//收集入口js文件
let globmaths = glob.sync(srcdir, {
  nodir: true, //忽略目录，表示仅仅查找目录下的所有js文件，对子目录不处理
})

let file_entry = globmaths.reduce((obj, file) => {
  let filename = path.basename(file).split(".")[0]
  //obj[filename] = ["babel-polyfill",file]
  obj[filename] = file
  return obj
}, {})

let entry = {}
for (var v in file_entry) {
  let file = file_entry[v]
  if (isModified(file)||prod) {
    entry[v] = file
  }
}
let keys = Object.keys(entry)
if (keys.length == 0) {
  console.log('----------没有可编译的文件, 终止，看的异常别紧张！----------')
  return
}

console.log('目标路径:',path.resolve(TARGET_DIR, tatdir))

module.exports = {
  entry: entry,
  output: {
    path: path.resolve(TARGET_DIR, tatdir),
    filename: "[name].js",
  },
  module: {
    rules: [
      //规则：支持处理js文件
      {
        test: /\.js$/,
        exclude: /(node_modules|bower_components)/,
        use: {
          loader: 'babel-loader?cacheDirectory',
          options: {
            presets: ['env'],
            plugins: ['transform-runtime']
          }
        }
      },
       //规则：支持处理pug文件
      {
          test: /\.pug$/,
          loader: 'pug-loader',
          options: {
            //  pretty: true
          }
        },
        //规则：读取.tpl.html结尾的文件为字符串
        //{ test: /\.tpl\.html$/, loader: 'string-loader' },
        {
          test: /\.tpl\.html$/,
          loader: 'string-loader',
        }
    ]
  },
  plugins: plugins
};
